// pages/goods_detail/index.js
import { request } from '../../request/index'
Page({

  /**
   * 页面的初始数据
   */
  data: {
     goodsObj: {}
  },
  // 商品对象
 GoodsInfo:{},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const {goods_id} = options
     console.log(options)
     console.log(goods_id)
     this.getGoodsDetail(goods_id)
  },
  async getGoodsDetail(goods_id) {
    const goodsObj = await request({url:'/goods/detail',data:{goods_id}})
    this.GoodsInfo = goodsObj.data.message
    this.setData({
      goodsObj:{  
        goods_name:goodsObj.data.message.goods_name,
        goods_price:goodsObj.data.message.goods_price,
        // 苹果部分手机不识别webp图片格式，要进行修改
        goods_introduce:goodsObj.data.message.goods_introduce.replace(/\.webp/g,'.jpg'),
        pics:goodsObj.data.message.pics
      }
    
    })
    console.log(goodsObj)
  },
  handlePrevewImage(e) {
    const urls = this.GoodsInfo.pics.map(v => v.pics_mid)
    console.log(urls)
    console.log(e)
    const current = e.currentTarget.dataset.url
    wx.previewImage({
      urls,
      current
    })
  },
  // 点击加入购物车事件
  handleCartAdd() {
     console.log(1)
    //  获取缓存中的购物车 数组
     let cart = wx.getStorageSync('cart') || [];
    //  判断 商品对象是否存在于购物车数组中
    let index = cart.findIndex(v => v.goods_id ===this.GoodsInfo.goods_id)
    if(index === -1) {
      this.GoodsInfo.checked = true
      this.GoodsInfo.num = 1
      cart.push(this.GoodsInfo)
    }else {
      cart[index].num++
    }
    wx.setStorageSync('cart', cart)
    wx.showToast({
      title: '加入成功',
      icon:'success',
      mask:true
    })
    console.log(cart)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})